﻿#region

using System;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Web.Mvc;
using CuongHanh.DAL;
using CuongHanh.Models;
using CuongHanh.Security;
using Ext.Net;
using Ext.Net.MVC;
using Image = System.Drawing.Image;

#endregion

namespace CuongHanh.Controllers.BO
{
    [CustomAuthorize(Key = "Management", Description = "Manage all apps")]
    public class ABannerController : ABaseController
    {
        private readonly UnitOfWork _unitOfWork = new UnitOfWork();

        public ActionResult Index(int branchId)
        {
            ViewBag.branchId = branchId;
            return View();
        }

        public ActionResult GetDatas(int branchId,
                int start,
                int limit,
                string sort,
                string query)
        {
            return Content(GetBannerByBranch(branchId,
                    start,
                    limit,
                    sort,
                    query),
                    "json");
        }

        public ActionResult GetBannerFromFolder(int branchId)
        {
            UpdateResult result = GetBannerFromRootFolder(branchId);
            ReloadStore("storeGvData");
            ShowNotification(result);
            return this.Direct();
        }

        public ActionResult Command(string containerId,
                                string command,
                                int id)
        {
            if (command == "ChangeBanner")
            {
                Banner model = GetBanner(id);
                return ShowWindow("ChangeBanner",
                                  containerId,
                                  model);
            }
            return this.Direct();
        }

        private Banner GetBanner(int id)
        {
            return _unitOfWork.FirstOrDefault<Banner>(c => c.Id == id);

        }

        public ActionResult UploadClick(Banner model)
        {
            string tpl = "Uploaded file: {0}<br/>Size: {1} bytes";

            if (this.GetCmp<FileUploadField>("FileUploadField1").HasFile)
            {
                FileUploadField fileUpload = this.GetCmp<FileUploadField>("FileUploadField1");
                byte[] imgData = fileUpload.FileBytes;


                ChangeBannerImage(model,
                        imgData,
                        fileUpload.FileContent);
                ResetForm("BasicForm");
                X.Msg.Show(new MessageBoxConfig
                {
                    Buttons = MessageBox.Button.OK,
                    Icon = MessageBox.Icon.INFO,
                    Title = "Success",
                    Message = string.Format(tpl,
                                            this.GetCmp<FileUploadField>("FileUploadField1").PostedFile.FileName,
                                            this.GetCmp<FileUploadField>("FileUploadField1").PostedFile.ContentLength)
                });
            }
            else
            {
                X.Msg.Show(new MessageBoxConfig
                {
                    Buttons = MessageBox.Button.OK,
                    Icon = MessageBox.Icon.ERROR,
                    Title = "Fail",
                    Message = "No file uploaded"
                });
            }
            DirectResult result = new DirectResult();
            result.IsUpload = true;
            return result;
        }

        #region Get Image From Folder

        public string GetBannerByBranch(int branchId,
                int start,
                int limit,
                string sort,
                string q)
        {
            IQueryable<Banner> query = _unitOfWork.Where<Banner>(c => c.BranchId == branchId && !c.Inactive);
            return FormatResult(query.Count(),
                    query.OrderBy(c => c.BannerTypeId).ThenBy(c => c.Image).Skip(start).Take(limit));
        }

        private UpdateResult GetBannerFromRootFolder(int branchId)
        {
            string curPath = Server.MapPath(AppUtil.GetBannerPath(branchId));
            if(!Directory.Exists(curPath))
                Directory.CreateDirectory(curPath);
            DirectoryInfo info = new DirectoryInfo(curPath);
            FileInfo[] files = info.GetFiles();
            DateTime dateTime = DateTime.Now;
            IQueryable<string> images = _unitOfWork.Where<Banner>(c => c.BranchId == branchId && c.BannerTypeId > 0 && !c.Inactive).Select(c => c.Image);
            files = files.Where(c => !images.Contains(c.Name)).ToArray();
            foreach (FileInfo file in files)
            {
                Image curImage = Image.FromFile(file.FullName);
                _unitOfWork.Insert(new Banner
                                   {
                                           BranchId = branchId,
                                           Image = file.Name,
                                           Width = curImage.Width,
                                           Height = curImage.Height,
                                           BannerTypeId = BannerType.Top,
                                           Show = true,
                                           Inactive = false,
                                           LastModified = dateTime
                                   });
            }
            _unitOfWork.Save();

            UpdateThumnailBanner(branchId);
            return new UpdateResult(1,
                    "Cập nhật thông tin banner thành công!");
        }

        private void UpdateThumnailBanner(int branchId)
        {
            string bannerPath = Server.MapPath(AppUtil.GetBannerPath(branchId));
            if(!Directory.Exists(bannerPath))
                Directory.CreateDirectory(bannerPath);

            string thumnailbannerPath = Server.MapPath(AppUtil.GetThumnailBannerPath(branchId));
            if(!Directory.Exists(thumnailbannerPath))
                Directory.CreateDirectory(thumnailbannerPath);

            IQueryable<Banner> banners = _unitOfWork.Where<Banner>(c => c.BranchId == branchId && !c.Inactive);
            foreach (Banner banner in banners)
            {
                if(System.IO.File.Exists(string.Format("{0}{1}",
                        bannerPath,
                        banner.Image)))
                    if(!System.IO.File.Exists(string.Format("{0}{1}",
                            thumnailbannerPath,
                            banner.Image)))
                    {
                        Bitmap map = new Bitmap(Image.FromFile(string.Format("{0}{1}",
                                bannerPath,
                                banner.Image)),
                                new Size(AppUtil.WIDTH_THUMNAIL_BANNER,
                                        (int) (((float) banner.Height / (float) banner.Width) * (float) AppUtil.WIDTH_THUMNAIL_BANNER)));
                        string[] temp = banner.Image.Split('.');
                        map.Save(string.Format("{0}{1}",
                                thumnailbannerPath,
                                banner.Image),
                                GetImageFormat(temp[temp.Length - 1]));
                    }
            }
        }

        #endregion
    }
}
